package com.tanhua.manager.controller;

import cn.hutool.captcha.LineCaptcha;
import com.tanhua.domain.db.Admin;
import com.tanhua.manager.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping(value = "/system/users/verification", name = "生成验证码")
    public void verification(String uuid, HttpServletResponse response) throws Exception {
        // 1、调用service生成验证码
        LineCaptcha lineCaptcha = adminService.verification(uuid);

        // 2、将验证码响应到客户端，指定mime类型
        response.setContentType("image/jpeg"); // 在web课程已经重点强调了（http协议传递的都是文本，如何视频、图片、html、xml等等）
        lineCaptcha.write(response.getOutputStream());
    }

    @PostMapping(value = "/system/users/login", name = "用户登录")
    public ResponseEntity login(@RequestBody Map<String, String> param) {
        String username = param.get("username");
        String password = param.get("password");
        String verificationCode = param.get("verificationCode");
        String uuid = param.get("uuid");
        String token = adminService.login(username, password, verificationCode, uuid);
        Map<String, String> loginResult = new HashMap<>();
        loginResult.put("token", token);
        return ResponseEntity.ok(loginResult);
    }

    @PostMapping(value = "/system/users/profile", name = "用户基本信息")
    public ResponseEntity profile(@RequestHeader("Authorization") String token) {
        Admin admin = adminService.findAdminByToken(token);
        return ResponseEntity.ok(admin);
    }

    @PostMapping(value = "/system/users/logout", name = "用户退出")
    public ResponseEntity logout(@RequestHeader("Authorization") String token) {
        adminService.logout(token);

        return ResponseEntity.ok(null);
    }
}
